package spouts;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;

public class CsvTweetSpout extends BaseRichSpout {

    private SpoutOutputCollector collector;

    private Scanner scanner;

    @Override
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        this.collector = collector;
        try {
            this.scanner = new Scanner(new File((String) conf.get("tweetFile")));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void nextTuple() {
        Utils.sleep(10);

        while (scanner.hasNextLine()) {
            final String rawTweet = scanner.nextLine();
            if (rawTweet != null && !rawTweet.isEmpty()) {
                collector.emit(new Values(rawTweet.substring(1, rawTweet.length() - 1).replaceAll("\"\"", "\"")));
            }
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("rawTweet"));
    }

    @Override
    public void close() {
        if (scanner != null) {
            scanner.close();
        }
    }
}
